<template>
  <div class="container">
    <!-- 自定义数据 -->
    <el-tree
      class="app-container"
      :data="depts"
      default-expand-all
      :props="defaultProps"
      :expand-on-click-node="false"
    >
      <template v-slot="{data}">
        <el-row type="flex" justify="space-between" align="middle" style="width: 100%;height:40px;">
          <el-col>{{ data.name }}</el-col>
          <el-col :span="4">
            <span>{{ data.managerName }}</span>
            <el-dropdown @command="deptsBtn($event, data.id)">
              <span class="el-dropdown-link">
                操作
                <i class="el-icon-arrow-down el-icon--right" />
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="add">添加子部门</el-dropdown-item>
                <el-dropdown-item command="edit">编辑部门</el-dropdown-item>
                <el-dropdown-item command="del">删除</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </el-col>
        </el-row>
      </template>
    </el-tree>
    <!-- 编辑组件 -->
    <!-- 接收子组件的时间 update:showwDialog 把传过来的值重新赋值给show-dialog -->
    <!-- updateDepartment 监听自定义事件 -->
    <AddDept
      ref="addDept"
      :current-node-id="currentNodeId"
      :show-dialog.sync="showDialog"
      @updateDepartment="getDepartment"
    />
  </div>
</template>

<script>
import { getDepartmentAPI, delDepartmentAPI } from '@/api/department'
import { transListToTreeData } from '@/utils'
import AddDept from '../components/addDept.vue'

export default {
  name: 'Department',
  components: { AddDept },
  data() {
    return {
      // 渲染数据
      depts: [],
      defaultProps: {
        children: 'children',
        name: 'name'
      },
      // 是否显示编辑组件
      showDialog: false,
      // 用户点击那一项的id
      currentNodeId: null
    }
  },
  created() {
    this.getDepartment()
  },
  methods: {
    // 获取数据
    async getDepartment() {
      const res = await getDepartmentAPI()
      this.depts = transListToTreeData(res, 0)
    },
    // 点击单项下拉菜单
    async deptsBtn(item, id) {
      if (item === 'add') {
        this.showDialog = true
        this.currentNodeId = id
      } else if (item === 'edit') {
        this.showDialog = true
        this.currentNodeId = id
        // 等待其他数据渲染完成(设计到异步) 获取到子组件的组件实例 相当于自组件的this 用来执行回去详情数据
        this.$nextTick(() => {
          this.$refs.addDept.getDeptmentDetails()
        })
      } else {
        this.$confirm('是否确定删除该数据', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          // 删除
          await delDepartmentAPI(id)
          // 提示
          this.$message.success('删除成功')
          // 重新获取数据
          this.getDepartment()
        })
      }
    }
  }
}
</script>

<style scoped lang="scss">
.container {
  .app-container {
    padding: 30px 130px;
    .el-dropdown-link {
      font-size: 14px;
      margin: 0 15px;
    }
  }
}
</style>
